package com.crysta1.aitrans;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class QuizActivity extends AppCompatActivity {

    private static final String TAG = "QuizActivity";

    private TextView tvQuestion, tvTimer;
    private EditText etAnswer;
    private Button btnGiveUp, btnConfirm;
    private String currentDifficulty, currentQuestion;
    private long timeElapsed = 0; // 毫秒
    private CountDownTimer timer;
    private DatabaseHelper dbHelper;
    private boolean isQuestionLoaded = false;

    private static final String API_KEY = "sk-9e6c74d4d0744a0ea018207f44d2cc74";
    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);

        Log.d(TAG, "onCreate: 初始化 QuizActivity");

        initViews();
        dbHelper = new DatabaseHelper(this);

        SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
        currentDifficulty = prefs.getString("difficulty", "M");
        Log.d(TAG, "当前难度: " + currentDifficulty);

        requestQuestionFromAI();
        setClickListeners();
    }

    private void initViews() {
        tvQuestion = findViewById(R.id.tvQuestion);
        tvTimer = findViewById(R.id.tvTimer);
        etAnswer = findViewById(R.id.etAnswer);
        btnGiveUp = findViewById(R.id.btnGiveUp);
        btnConfirm = findViewById(R.id.btnConfirm);

        btnConfirm.setEnabled(false);

        etAnswer.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                btnConfirm.setEnabled(s.toString().trim().length() > 0 && isQuestionLoaded);
            }
        });
    }

    private void requestQuestionFromAI() {
        tvQuestion.setText("正在生成题目...");
        Log.d(TAG, "开始请求AI生成题目...");

        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();

            JSONObject bodyJson = new JSONObject();
            try {
                bodyJson.put("model", "deepseek-chat");
                bodyJson.put("temperature", 0.7);
                bodyJson.put("max_tokens", 150);

                JSONArray messages = new JSONArray();
                JSONObject userMsg = new JSONObject();

                String userPrompt = "请出一题英译中翻译题，只返回一句完整可显示给用户的句子。" +
                        " 难度说明：" +
                        "简单 = 中考水平，" +
                        "适中 = 四级水平，" +
                        "困难 = 六级水平，可能包含长难句，" +
                        "仿真 = 历届考研阅读/翻译，可能包含长难句。" +
                        " 返回 JSON 格式：{\"exam_question\":\"题目内容\"}" +
                        " 当前时间戳：" + System.currentTimeMillis();

                userMsg.put("role", "user");
                userMsg.put("content", userPrompt);
                messages.put(userMsg);

                bodyJson.put("messages", messages);
            } catch (JSONException e) {
                Log.e(TAG, "构建请求 JSON 失败: ", e);
            }

            RequestBody body = RequestBody.create(bodyJson.toString(), MediaType.get("application/json"));
            Request request = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + API_KEY)
                    .addHeader("Content-Type", "application/json")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String respStr = response.body().string();
                Log.d(TAG, "AI 返回题目响应: " + respStr);

                runOnUiThread(() -> {
                    try {
                        JSONObject root = new JSONObject(respStr);
                        String content = root.getJSONArray("choices")
                                .getJSONObject(0)
                                .getJSONObject("message")
                                .getString("content");

                        JSONObject contentJson = new JSONObject(content);
                        currentQuestion = contentJson.getString("exam_question");

                        tvQuestion.setText(currentQuestion);
                        isQuestionLoaded = true;
                        startTimer();
                    } catch (Exception e) {
                        Log.e(TAG, "题目解析失败: ", e);
                        tvQuestion.setText("题目解析失败，请重试");
                        Toast.makeText(this, "题目解析失败", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                Log.e(TAG, "请求AI题目失败: ", e);
                runOnUiThread(() -> {
                    tvQuestion.setText("请求失败，请检查网络");
                    Toast.makeText(this, "请求失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    private void startTimer() {
        Log.d(TAG, "开始计时...");
        timer = new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeElapsed += 1000;
                updateTimerText();
            }
            @Override public void onFinish() {}
        }.start();
    }

    private void updateTimerText() {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(timeElapsed);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(timeElapsed) -
                TimeUnit.MINUTES.toSeconds(minutes);
        tvTimer.setText(String.format(Locale.getDefault(), "用时: %02d:%02d", minutes, seconds));
    }

    private void setClickListeners() {
        btnGiveUp.setOnClickListener(v -> {
            Log.d(TAG, "用户点击放弃");
            if (timer != null) timer.cancel();

            long timestamp = System.currentTimeMillis();
            dbHelper.addQuizRecord(
                    currentQuestion, "", timeElapsed / 1000,
                    -1, currentDifficulty, "用户放弃答题", timestamp
            );
            Toast.makeText(this, "已放弃本题", Toast.LENGTH_SHORT).show();
            finish();
        });

        btnConfirm.setOnClickListener(v -> {
            Log.d(TAG, "用户点击确认答案");
            if (timer != null) timer.cancel();

            String answer = etAnswer.getText().toString().trim();
            long timeSpent = timeElapsed / 1000;

            submitAnswerForGrading(answer, timeSpent);
        });
    }

    private void submitAnswerForGrading(final String answer, final long timeSpent) {
        tvQuestion.setText("正在评分...");
        btnConfirm.setEnabled(false);
        btnGiveUp.setEnabled(false);
        Log.d(TAG, "提交答案给AI评分: " + answer);

        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();

            JSONObject bodyJson = new JSONObject();
            try {
                bodyJson.put("model", "deepseek-chat");
                bodyJson.put("temperature", 0.7);
                bodyJson.put("max_tokens", 150);

                JSONArray messages = new JSONArray();
                JSONObject userMsg = new JSONObject();

                String userPrompt = "题目: " + currentQuestion +
                        "\n用户答案: " + answer +
                        "\n答题耗时: " + timeSpent + " 秒。" +
                        "\n评分要求: 满分10.00分。简单、适中模式酌情给高分；困难模式稍微刁钻一些；仿真模式客观给分。" +
                        " 如果答题耗时过长，适当扣分。" +
                        " 请返回 JSON 格式：{\"score\":分数, \"feedback\":\"反馈\"}" +
                        " 当前时间戳：" + System.currentTimeMillis();

                userMsg.put("role", "user");
                userMsg.put("content", userPrompt);
                messages.put(userMsg);

                bodyJson.put("messages", messages);
            } catch (JSONException e) {
                Log.e(TAG, "构建评分 JSON 失败: ", e);
            }

            RequestBody body = RequestBody.create(bodyJson.toString(), MediaType.get("application/json"));
            Request request = new Request.Builder()
                    .url(API_URL)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + API_KEY)
                    .addHeader("Content-Type", "application/json")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String respStr = response.body().string();
                Log.d(TAG, "AI 返回评分响应: " + respStr);

                runOnUiThread(() -> {
                    try {
                        JSONObject root = new JSONObject(respStr);
                        String content = root.getJSONArray("choices")
                                .getJSONObject(0)
                                .getJSONObject("message")
                                .getString("content");

                        JSONObject contentJson = new JSONObject(content);
                        float score = (float) contentJson.getDouble("score");
                        String feedback = contentJson.getString("feedback");

                        long timestamp = System.currentTimeMillis(); // 当前答题完成时间
                        dbHelper.addQuizRecord(currentQuestion, answer, timeSpent,
                                score, currentDifficulty, content, timestamp);

                        showResult(score, feedback);
                    } catch (Exception e) {
                        Log.e(TAG, "评分解析失败: ", e);
                        tvQuestion.setText("评分解析失败，请重试");
                        Toast.makeText(this, "评分解析失败", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                Log.e(TAG, "请求AI评分失败: ", e);
                runOnUiThread(() -> {
                    tvQuestion.setText("评分请求失败，请检查网络");
                    Toast.makeText(this, "评分失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }

    private void showResult(float score, String feedback) {
        Log.d(TAG, "显示结果: 分数=" + score + "，反馈=" + feedback);
        ResultDialog dialog = new ResultDialog(this, score, feedback);
        dialog.setFinishListener(this::finish);
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) timer.cancel();
        Log.d(TAG, "onDestroy: 计时器已取消");
    }
}
